<template>
    <div class="QilinUploadFile">
        <el-upload
            ref="uploadFileRef"
            :action="ownUploadFileConfig.action || '#' "
            :headers="ownUploadFileConfig.headers || {}"
            :list-type="ownUploadFileConfig.listType || 'text' "
            :auto-upload="ownUploadFileConfig.autoUpload || false "
            :limit="ownUploadFileConfig.limit || 5"
            :drag="ownUploadFileConfig.drag === false ? false : true "
            :file-list="ownUploadFileConfig.fileList || [] "
            :multiple="ownUploadFileConfig.multiple === false ? false : true "
            :disabled="ownUploadFileConfig.disabled || false"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-error="handleError"
        >
            <el-icon class="el-icon-upload"></el-icon>
            <div class="el-upload__text">
                <span>{{ownUploadFileConfig.uploadText || "拖入此处上传或点击上传"}}</span>
                <div>{{ownUploadFileConfig.fileTypeText || "（支持xls、word、pdf文件格式）"}}</div>
            </div>
        </el-upload>
        <div class="QilinUploadFile-list">
            <div class="QilinUploadFile-list-item"
                v-for="(item,index) in ownUploadFileConfig.fileList"
                :key="item[(ownUploadFileConfig.fileOptions && ownUploadFileConfig.fileOptions.serverUrl) || 'fileName'] || 'filelist-key'+index"
            >
                <el-icon class="el-icon-document"></el-icon>
                <span @click="ownUploadFileConfig.previewFn && ownUploadFileConfig.previewFn(item)">
                    {{ownUploadFileConfig.action ? item[(ownUploadFileConfig.fileOptions && ownUploadFileConfig.fileOptions.serverName) || 'newFileName'] : item.name}}
                </span>
                <el-icon class="el-icon-download" @click.native="ownUploadFileConfig.downloadFn && ownUploadFileConfig.downloadFn(item)" title="下载"></el-icon>
                <el-icon class="el-icon-delete" @click.native="deleteFile(index,item)" title="删除"></el-icon>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name:"QilinUploadFile",
    props:{
        uploadFileConfig:{
            type:Object,
            default(){
                return {
                    action:"#", //文件上传至服务器url
                    headers:{}, //设置上传的请求头部--当action有值时必填，用以设置token等
                    listType:"text", //文件列表类型
                    autoUpload:false, //是否自动上传，当action有值时，则autoUpload须为true
                    limit:5, //文件允许上传数量
                    fileList:[], //默认上传文件--必填
                    multiple:true, //是否支持多选文件
                    drag:true, //是否启用拖拽上传
                    disabled:false, //是否禁用上传
                    uploadText:"拖入此处上传或点击上传", //上传文字说明
                    fileTypeText:"（支持xls、word、pdf文件格式）", //支持格式文字说明
                    fileType:["xls","xlsx","doc","docx","pdf"], //支持上传的文件类型
                    fileSize:20 * 1000 * 1000, //文件上传大小限制20M之内默认
                    previewFn:"event", //点击文件名称触发事件
                    downloadFn:"event", //点击文件下载图标触发事件
                    fileOptions:{ //文件设置配置项
                        serverOriginalName:"originalFilename", //文件上传至后端，返回的原始文件名称
                        serverName:"newFileName", //文件上传至后端，返回的文件名称--用以回显文件的名称
                        serverUrl:"fileName", //文件上传至后端，返回的文件url地址--用以回显文件的url
                        responseDataName:"data", //文件上传至服务器，返回的响应字段，默认为data，通常也是data
                    }
                }
            }
        },
        fileList:{ //用以回显
            type:[Array,String],
            default(){
                return []
            }
        }
    },
    data(){
        return {

        }
    },
    computed:{
        ownUploadFileConfig:{
            get(){
                this.uploadFileConfig.fileList=this.fileList ? ( typeof this.fileList === "string" ? JSON.parse(this.fileList) : this.fileList || [] ) : [] ;
                return this.uploadFileConfig;
            },
            set(val){
                this.$emit("update:uploadFileConfig",val);
            }
        }
    },
    methods:{
        /**
         *  **当action为指定服务器地址时
         */
        // 文件上传之前的事件监听
        handleBeforeUpload(file){
            // console.log(file,this.ownUploadFileConfig.action);
            if(!this.ownUploadFileConfig.action || this.ownUploadFileConfig.action === "#") return ;
            const index=file.name.lastIndexOf(".");
            const fileType=file.name.slice(index+1).toLowerCase();
            if(this.ownUploadFileConfig.fileType && !this.ownUploadFileConfig.fileType.includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的文件",
                    type:"warning"
                });
                return false;
            }else if(!this.ownUploadFileConfig.fileType && !["xls","xlsx","doc","docx","pdf"].includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的文件",
                    type:"warning"
                });
                return false;
            }else if(file.size > (this.ownUploadFileConfig.fileSize || 20 * 1000 * 1000)){
                this.$message({
                    message:"文件大小超过限制",
                    type:"warning"
                });
                return false;
            };
        },
        // 文件上传成功后的事件监听
        handleSuccess(response,file,fileList){
            // console.log(response,file,fileList,"========");
            this.$emit("actionSuccess",response,file);
        },
        // 文件上传失败后的事件监听
        handleError(error,file,fileList){
            // console.log(error,file,fileList,"========");
            this.$nextTick(()=>{
                this.$refs["uploadFileRef"].handleRemove(file);
            });
        },

        /**
         *  **当action未填写时
         */
        // 文件上传状态改变事件监听
        handleChange(file,files){
            // console.log(file,files);
            if(this.ownUploadFileConfig.action) return ;
            const index=file.name.lastIndexOf(".");
            const fileType=file.name.slice(index+1).toLowerCase();
            if(this.ownUploadFileConfig.fileType && !this.ownUploadFileConfig.fileType.includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的文件",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadFileRef"].handleRemove(file);
                });
            }else if(!this.ownUploadFileConfig.fileType && !["xls","xlsx","doc","docx","pdf"].includes(fileType)){
                this.$message({
                    message:"请上传符合格式要求的文件",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadFileRef"].handleRemove(file);
                });
            }else if(file.size > (this.ownUploadFileConfig.fileSize || 20 * 1000 * 1000)){
                this.$message({
                    message:"文件大小超过限制",
                    type:"warning"
                });
                this.$nextTick(()=>{
                    this.$refs["uploadFileRef"].handleRemove(file);
                });
            }else{
                this.ownUploadFileConfig.fileList.push({
                    raw:file.raw,
                    name:file.name
                });
                this.$emit("success",this.ownUploadFileConfig.fileList,file);
            };
        },

        // 超出限制时的事件监听
        handleExceed(files,uploadFiles){
            // console.log(files,uploadFiles);
            this.$message({
                message:"文件上传数量不能大于"+(this.ownUploadFileConfig.limit || 5 )+"个",
                type:"warning"
            });
        },
        // 移除文件时的事件监听
        handleRemove(uploadFile,uploadFiles){
            // console.log(uploadFile,uploadFiles);
        },
        // 点击删除文件图标事件监听
        deleteFile(index,item){
            // console.log(this.ownUploadFileConfig.fileList,item);
            this.ownUploadFileConfig.fileList.splice(index,1);
            this.$emit("success",this.ownUploadFileConfig.fileList,index);
        }
    },
    mounted(){

    }
}
</script>

<style lang="scss" scoped>
.QilinUploadFile{
    width:100%;
    >div:first-child{
        width:65%;
        :deep(.el-upload){
            width:100%;
            >.el-upload-dragger{
                width:100%;
                height:auto;
                padding:20px;
                >i{
                    font-size:32px;
                    margin:0;
                }
            }
            .el-upload__text{
                >span{
                    color:$common-text-color;
                    font-size:$small-text-size;
                }
                >div{
                    color:$support-text-color;
                    font-size:$small-text-size;
                    line-height:20px;
                }
            }
        }
    }
    >.QilinUploadFile-list{
        width:65%;
        >.QilinUploadFile-list-item{
            display:flex;
            align-items:center;
            justify-content: space-between;
            margin:10px 0;
            line-height:1.5;
            >span{
                color:$primary-text-color;
                margin:0 6px 0 3px;
                cursor:pointer;
                flex:1;
                min-width:0;
                white-space:nowrap;
                overflow:hidden;
                text-overflow:ellipsis;
            }
            >i{
                color:$primary-text-color;
                margin:0 5px;
                cursor:pointer;
            }
        }
    }
}
</style>
